<template>
  <el-form
    ref="ruleFormRef"
    style="max-width: 600px"
    :model="ruleForm"
    :rules="rules"
    label-width="auto"
    class="demo-ruleForm"
    :size="formSize"
    status-icon
  >
    <el-form-item label="BOM编号" prop="bomNum">
      <el-input v-model="ruleForm.bomNum" />
      <el-checkbox
        v-model="systemNumberChecked"
        @change="generateSystemNumber"
        name="type"
        >系统编号</el-checkbox
      >
    </el-form-item>
    <el-form-item label="BOM主题" prop="bomTopic">
      <el-input v-model="ruleForm.bomTopic" />
    </el-form-item>
    <el-form-item label="版本" prop="versions">
      <el-input v-model="ruleForm.versions" />
    </el-form-item>
    <el-form-item label="成品类型" prop="artifactType">
      <el-select
        v-model="ruleForm.artifactType"
        placeholder="请选择"
        size="large"
        style="width: 240px"
      >
        <el-option
          v-for="item in tableData"
          :key="item.ArtifactId"
          :label="item.ArtifactName"
          :value="item.ArtifactName"
        />
      </el-select>
    </el-form-item>
    <el-form-item label="日产量" prop="dailyOutput">
      <el-input v-model="ruleForm.dailyOutput" />
    </el-form-item>
    <el-form-item label="成品名称" prop="artifactName">
      <el-input
        v-model="ruleForm.artifactName"
        @click="dialogTableVisible = true"
      />
    </el-form-item>
    <el-form-item label="备注" prop="remark">
      <el-input v-model="ruleForm.remark" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm(ruleFormRef)">
        添加Bom
      </el-button>
      <el-button @click="resetForm(ruleFormRef)">重置</el-button>
    </el-form-item>
  </el-form>
  <!-- 产品列表弹出框开始 -->
  <el-dialog v-model="dialogTableVisible" title="选择产品" width="800">
    <el-form :inline="true" :model="formInline" class="demo-form-inline">
      <el-form-item label="产品名称">
        <el-input
          v-model="formInline.product_Name"
          placeholder="请输入产品名称"
          clearable
        />
      </el-form-item>
      <el-form-item label="规格型号">
        <el-input
          v-model="formInline.model_Number"
          placeholder="请输入规格型号"
          clearable
        />
      </el-form-item>
      <el-form-item label="品牌">
        <el-input
          v-model="formInline.brand"
          placeholder="请输入品牌"
          clearable
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="fetchData">查询</el-button>
      </el-form-item>
    </el-form>
    <el-table
      ref="multipleTableRef"
      :data="tableDatas"
      border
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column label="产品编号" align="center">
        <!-- 使用 row.Product_Code 显示产品编号 -->
        <template v-slot="slot">
          {{ slot.row.Product_Code }}
        </template>
      </el-table-column>
      <el-table-column
        prop="Product_Name"
        label="产品名称"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="Model_Number"
        label="规格型号"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="Brand"
        label="品牌"
        align="center"
      ></el-table-column>
      <el-table-column label="单位" align="center">
        <template v-slot="slot">
          <!-- 使用 row.UnitName 显示单位名称 -->
          {{ slot.row.Unit_Id }}
        </template>
      </el-table-column>
      <el-table-column label="产品分类" align="center">
        <template v-slot="slot">
          <!-- 使用 row.TypeName 显示产品类别名称 -->
          {{ slot.row.Product_Category_Id }}
        </template>
      </el-table-column>
      <el-table-column label="产品属性" align="center">
        <template v-slot="slot">
          <!-- 使用 row.AttName 显示产品属性名称 -->
          {{ slot.row.Product_Attributes_Id }}
        </template>
      </el-table-column>
      <el-table-column prop="Unit_Price" label="销售单价" align="center">
        <template v-slot="slot">
          <!-- 使用 row.UnitPrice 显示销售单价 -->
          {{ slot.row.Unit_Price.toFixed(2) }}
        </template>
      </el-table-column>
      <el-table-column
        prop="Minimum_Stock_Quantity"
        label="最小库存数"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="Maximum_Stock_Quantity"
        label="最大库存数"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="Product_Expiry_Date"
        label="产品有效期"
        align="center"
      >
        <template v-slot="slot">
          <!-- 使用 row.MatDate 显示日期 -->
          {{ slot.row.Product_Expiry_Date.substr(0, 10) }}
        </template>
      </el-table-column>
      <el-table-column
        prop="Alert_Days"
        label="报警天数"
        align="center"
      ></el-table-column>
      <el-table-column prop="Status" label="状态" align="center">
        <template v-slot="slot">
          <!-- 使用 row.TypeName 显示产品类别名称 -->
          <span v-if="slot.row.Status == 1">启用</span>
          <span v-else="slot.row.Status == 2">禁用</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="Remarks"
        label="备注"
        align="center"
      ></el-table-column>
      <el-table-column prop="Product_Image" label="产品图片" align="center">
        <template v-slot="slot">
          <img
            :src="'http://localhost:5055/PIC/' + slot.row.Product_Image"
            style="width: 55px; height: 55px"
          />
        </template>
      </el-table-column>
    </el-table>
    <table style="margin: auto">
      <tr>
        <td>
          <el-pagination
            v-model:current-page="page"
            v-model:page-size="size"
            :page-sizes="[10, 20, 30, 40]"
            :small="small"
            :disabled="disabled"
            :background="background"
            layout="total, sizes, prev, pager, next, jumper"
            :total="totalCount"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </td>
      </tr>
    </table>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogTableVisible = false">取消</el-button>
        <el-button type="primary" @click="addProduct"> 确定 </el-button>
      </div>
    </template>
  </el-dialog>
  <!-- 产品列表弹出框结束 -->
</template>

<script lang="ts" setup>
import { reactive, ref } from "vue";
import type { FormInstance, FormRules } from "element-plus";
import axios from "axios";
import { ElMessage } from "element-plus";
//引用路由
import { useRouter } from "vue-router";
import { formatDate } from "../outtabs(库存管理)/filter.js";
const router = useRouter();
interface RuleForm {
  bomNum: string;
  bomTopic: string;
  versions: string;
  artifactType: string;
  dailyOutput: number;
  artifactName: string;
  remark: string;
  quantity: number;
  parentProductId: number;
  childProductId: number;
}
const formInline = reactive({
  // 表单数据
  product_Name: "",
  model_Number: "",
  brand: "",
});
//定义弹出框产品列表
const tableDatas = ref([]);
const totalCount = ref(0);
const page = ref(1);
const size = ref(10);
const units = ref([]); // 单位下拉列表数据
const materialTypes = ref([]); // 物料类别下拉列表数据
const materialProperties = ref([]); // 物料属性下拉列表数据
const small = ref(true);
//定义弹出框默认值
const dialogTableVisible = ref(false);
//多选框勾选列表
const multipleTableRef = ref([]);
const formSize = ref("default");
const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive<RuleForm>({
  bomNum: "",
  bomTopic: "",
  versions: "",
  artifactType: "",
  dailyOutput: "",
  artifactName: "",
  remark: "",
  quantity: "",
  parentProductId: "",
  childProductId: "",
});
const tableData = ref([]);
const rules = reactive<FormRules<RuleForm>>({
  bomNum: [{ required: true, message: "请输入BOM单号", trigger: "blur" }],
  bomTopic: [{ required: true, message: "请输入BOM主题", trigger: "blur" }],
  versions: [{ required: true, message: "请输入版本", trigger: "blur" }],
  artifactType: [
    {
      required: true,
      message: "请选择成品类型",
      trigger: "change",
    },
  ],
  dailyOutput: [
    { required: true, message: "请输入日产量", trigger: "blur" },
    { pattern: /^[1-9]\d*$/, message: "日产量必须为正整数" },
  ],
  artifactName: [
    { required: true, message: "请输入成品名称", trigger: "blur" },
  ],
  remark: [{ required: true, message: "请输入备注", trigger: "blur" }],
});
const handleSizeChange = (val) => {
  size.value = val;
  fetchData();
};

const handleCurrentChange = (val) => {
  page.value = val;
  fetchData();
};

const fetchData = async () => {
  try {
    const response = await axios.get(
      `Product/GetUserListByKeyword?page=${page.value}&size=${size.value}&product_Name=${formInline.product_Name}&model_Number=${formInline.model_Number}&brand=${formInline.brand}`
    );
    if (response.data.Data && response.data.Data.length > 0) {
      tableDatas.value = response.data.Data;
      totalCount.value = response.data.TotalCount;
    } else {
      tableDatas.value = [];
      totalCount.value = 0;
    }
  } catch (error) {
    console.error("Error fetching data:", error);
  }
};
const fetchDropdownData = async () => {
  try {
    const [unitsRes, materialTypesRes, materialPropertiesRes] =
      await Promise.all([
        axios.get("Materials/GetMatUnitInfoShow"),
        axios.get("Materials/GetMatTypeinfoShow"),
        axios.get("Materials/GetMatattrShow"),
      ]);
    units.value = unitsRes.data;
    materialTypes.value = materialTypesRes.data;
    materialProperties.value = materialPropertiesRes.data;
  } catch (error) {
    console.error("Error fetching dropdown data:", error);
  }
};
//获取多选框选中的值
const handleSelectionChange = (val) => {
  // multipleTableRef.value = val.map(item => item.label);
  // console.log(multipleTableRef.value)
  if (val.length > 1) {
    ElMessage.error("请选择且只选择一条生产单号");
    return;
  }
  ruleForm.artifactName = val[0].Product_Name;
};
//弹出框添加产品信息
const addProduct = () => {
  // //判断多选框长度
  // if (multipleTableRef.value.length !== 1) {
  //   ElMessage.error('请选择且只选择一条生产单号');
  //   return;
  // }
  // // 遍历 tableDatas 数组获取 name 属性值
  // const names = tableDatas.map(tableDatas => tableDatas.name);

  // // 如果需要将所有 name 组成一个字符串并用逗号分隔
  // const namesString = names.join(', ');
  // // 获取第一个逗号前的数据
  // const firstDataBeforeComma = namesString.split(',')[0].trim();
  // // 将获取到的 name 属性值赋值给 ruleForm.artifactName
  // ruleForm.artifactName = firstDataBeforeComma;
  // 关闭弹出框
  dialogTableVisible.value = false;
};
const getArtifacList = () => {
  axios.get("BOM/GetArtifacTypeList").then((res) => {
    tableData.value = res.data;
  });
};
const systemNumberChecked = ref(false);

const generateSystemNumber = () => {
  if (systemNumberChecked.value) {
    ruleForm.bomNum = "BOM" + formatDate(new Date(), "yyyymdhis");
  } else {
    //ruleForm.bomNum = "BOM" + formatDate(new Date(), "yyyymdhis");
     ruleForm.bomNum = '';
  }
};
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      axios.post("BOM/AddBom", ruleForm).then((res) => {
        if (res.data > 0) {
          ElMessage.success("Bom添加成功");
          router.push("/UserList/showbomInfo");
        } else {
          ElMessage.error("Bom添加失败");
        }
      });
    } else {
      console.log("error submit!", fields);
    }
  });
};

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};

const options = Array.from({ length: 10000 }).map((_, idx) => ({
  value: `${idx + 1}`,
  label: `${idx + 1}`,
}));
getArtifacList();
fetchData();
fetchDropdownData();
</script>
<style>
#app {
  max-width: 100%;
  margin: 0 auto;
  padding: 0rem;
  font-weight: normal;
  width: 1800px;
}
</style>
